/*
 * Copyright (C) ${year} Jeffrey Palm.
 *
 * This code is part of the Floto Project (http://jeffpalm.com/floto/).
 * Please consult the LICENSE included in the distribution.
 */
package com.jeffpalm.floto.isight.app;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.jeffpalm.floto.isight.ConfigInstance;

public final class OptionsPanel extends JPanel {

  private static final long serialVersionUID = 1L;
  private final OptionPane[] panes;

  public OptionsPanel(OptionPane[] panes) {
    this.panes = new OptionPane[panes.length];
    System.arraycopy(panes, 0, this.panes, 0, panes.length);
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    add(new JLabel("Options"));
    for (int i = 0; i < panes.length; i++)
      add(panes[i]);
  }

  public void save() {
    for (int i = 0; i < panes.length; i++) {
      panes[i].save();
    }
  }

  public static class OptionPane extends JPanel {

    private static final long serialVersionUID = 1L;
    private final JTextField text = new JTextField(40);
    private final String prop;
    private final ConfigInstance config;

    OptionPane(ConfigInstance config, String title, String prop, String defaultValue) {
      this(config, title, prop, defaultValue, false);
    }

    OptionPane(ConfigInstance config, String title, String prop, String defaultValue, boolean showBrowse) {
      this.config = config;
      this.prop = prop;
      setBorder(BorderFactory.createTitledBorder(title));
      text.setText(config.get(prop, defaultValue));
      add(text);
      if (showBrowse) {
        add(new JButton(new AbstractAction("Browse...") {

          private static final long serialVersionUID = 1L;

          public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int res = fc.showOpenDialog(null);
            if (res != JFileChooser.APPROVE_OPTION) return;
            File f = fc.getSelectedFile();
            if (f == null) return;
            text.setText(f.getAbsolutePath());
          }
        }));
      }
    }

    public void save() {
      config.set(prop, text.getText());
    }

  }

  public static OptionPane P(ConfigInstance config, String title, String prop, String defaultValue) {
    return new OptionPane(config,title,prop,defaultValue);
  }

  public static OptionPane P(ConfigInstance config, String title, String prop, String defaultValue, boolean showBrowse) {
    return new OptionPane(config,title,prop,defaultValue,showBrowse);
  }

}